﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    public static class Extensions
    {
        #region Json

        public static object ToJsonObject(this string jsonStr)
        {
            object obj = JsonConvert.DeserializeObject(jsonStr);
            return obj;
        }

        public static T ToJsonObject<T>(this string jsonStr)
        {
            T obj = JsonConvert.DeserializeObject<T>(jsonStr);
            return obj;
        }

        public static string ToJson(this object obj)
        {
            string strSerializeJson = JsonConvert.SerializeObject(obj);
            return strSerializeJson;
        }

        #endregion

        public static bool In<T>(this T obj, params T[] args)
        {
            return args.Contains(obj);
        }

        public static void ForEach<T>(this IEnumerable<T> items, Action<T> action, Boolean safe = true)
        {
            if (safe)
            {
                foreach (T item in items.ToList())
                    action(item);
                return;
            }

            foreach (T item in items)
                action(item);
        }

        public static List<T> ConvertAll<s, T>(this IEnumerable<s> source, Converter<s, T> converter)
        {
            return new List<s>(source).ConvertAll(converter);
        }

        public static List<T> FindAll<T>(this IEnumerable<T> source, Predicate<T> predicate)
        {
            return new List<T>(source).FindAll(predicate);
        }
    }
}
